using System;
using System.Collections.Generic;

namespace Client.Base
{
    public class StateMachine<T>
    {
        private T currentState;
        private readonly Dictionary<T, StateDefinition> stateDict = new();

        public StateMachine(T initialState)
        {
            currentState = initialState;
        }


        public void AddState(T tag, Action onEnter, Action onExit)
        {
            if (!stateDict.TryGetValue(tag, out var state))
            {
                state = new StateDefinition
                {
                    OnEnter = onEnter,
                    OnExit = onExit
                };
                stateDict.Add(tag, state);
            }
        }

        public bool TryTransition(T trigger)
        {
            if (!CanTransition(trigger))
                return false;


            if (!CanTransition(currentState))
                return false;

            stateDict[currentState].OnExit?.Invoke();
            currentState = trigger;
            stateDict[currentState].OnEnter?.Invoke();
            return true;
        }

        public void Execute()
        {
            if (stateDict.TryGetValue(currentState, out var state))
            {
                state.OnEnter.Invoke();
            }
        }
        private bool CanTransition(T trigger)
        {
            return stateDict.ContainsKey(trigger);
        }
    }
}

